// Copyright (C) Kumo inc. and its affiliates.
// Author: Jeff.li lijippy@163.com
// All rights reserved.
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published
// by the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program.  If not, see <https://www.gnu.org/licenses/>.
//

package handler

import (
	"encoding/json"
	"net/http"

	"github.com/kumose/fn"
	logprinter "github.com/kumose/kmopt/pkg/logger/printer"
	"github.com/kumose/kmopt/pkg/repository"
	"github.com/kumose/kmopt/pkg/repository/model"
	"github.com/kumose/kmopt/pkg/repository/v1manifest"
)

// RotateRoot handles requests to re-sign root manifest
func RotateRoot(mirror repository.Mirror) http.Handler {
	return &rootSigner{mirror}
}

type rootSigner struct {
	mirror repository.Mirror
}

func (h *rootSigner) ServeHTTP(w http.ResponseWriter, r *http.Request) {
	fn.Wrap(h.sign).ServeHTTP(w, r)
}

func (h *rootSigner) sign(m *v1manifest.RawManifest) (sr *simpleResponse, err statusError) {
	root := v1manifest.Root{}
	if err := json.Unmarshal(m.Signed, &root); err != nil {
		logprinter.Errorf("Unmarshal manifest %s", err.Error())
		return nil, ErrorInvalidManifest
	}

	manifest := &v1manifest.Manifest{
		Signatures: m.Signatures,
		Signed:     &root,
	}

	switch err := h.mirror.Rotate(manifest); err {
	case model.ErrorConflict:
		return nil, ErrorManifestConflict
	case nil:
		return nil, nil
	default:
		logprinter.Errorf("Rotate root manifest: %s", err.Error())
		return nil, ErrorInternalError
	}
}
